package edu.zjut.hjg.saas.kwmp.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.service.KindergartenService;
import edu.zjut.hjg.saas.kwmp.web.exception.NoEnabledAppFoundException;
import edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants;

public class AppMappingInterceptor extends HandlerInterceptorAdapter {

    private KindergartenService kindergartenService;

    public void setKindergartenService(KindergartenService kindergartenService) {
        this.kindergartenService = kindergartenService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String serverName = request.getServerName();
        Kindergarten app = kindergartenService.findBySiteDomain(serverName);
        if (app == null || !app.isEnabled()) {
            // 应用不存在或未启用
            throw new NoEnabledAppFoundException();
        }
        request.setAttribute(KwmpConstants.RQUEST_ATTRIBUTE_APP, app);
        return super.preHandle(request, response, handler);
    }
}
